package main

import (
    "fmt"
    "io"
    "os"
    "github.com/chzyer/readline"
    "strings"

)

func main() {



    promote, err := readline.NewEx(&readline.Config{
        Prompt:            "prowatcher>",
        HistoryFile:       "/tmp/his.tmp",
        AutoComplete:      completer,
        InterruptPrompt:   "^C",
        EOFPrompt:         "exit",
        HistorySearchFold: true,
    })
    if err != nil {
        fmt.Println(err)
        os.Exit(2)
    }
    defer promote.Close()

    nodes := Nodes{
        map[string]*Node{
            "test": &Node{
                addr: "127.0.0.1:9999",
            },
        },
        nil,
    }

    for {
        line, err := promote.Readline()
        if err == readline.ErrInterrupt {
            if len(line) == 0 {
                break
            } else {
                continue
            }
        } else if err == io.EOF {
            break
        }
        line = strings.TrimSpace(line)
        cmd, opt, target := parseCommand(line)
        switch cmd {
        case "check":
            err := nodes.check(opt, target, promote)
            if err != nil {
                io.WriteString(promote, fmt.Sprintf("error: %v", err))
            }
        case "status":
            err := nodes.status(opt, target, promote)
            if err != nil {
                io.WriteString(promote, fmt.Sprintf("error: %v", err))
            }
        case "run":
        case "commands":
        case "check-to-run":
        case "help":
            HelpCommand(opt, target, promote)
        default:
            io.WriteString(promote, "command not support, use:  help")
        }
    }
}

func parseCommand(line string) (cmd string, options []string, target []string) {
    for i, s := range strings.Split(line, " ") {
        if s == "" {
            continue
        } else if i == 0 {
            cmd = s
            continue
        } else if strings.HasPrefix(s, "-") {
            options = append(options, s)
            continue
        } else {
            target = append(target, s)
            continue
        }
    }
    return
}

type Command func([]string, []string, io.Writer) error //node flags target

var completer = readline.NewPrefixCompleter(
    readline.PcItem("check", readline.PcItem("-refresh"), readline.PcItem("-more"), ),
    readline.PcItem("status", ),
    readline.PcItem("run", ),
    readline.PcItem("help", ),
    readline.PcItem("commands", ),
    readline.PcItem("check-to-run", ),
)

func HelpCommand(_ []string, _ []string, w io.Writer) error {
    io.WriteString(w, "usage:\n")
    io.WriteString(w, completer.Tree("    "))
    return nil
}